<template>
  <a-card class="general-card" title="直播管理" :bordered="false">
    <a-row style="margin-bottom: 16px">
      <a-radio-group v-model="type" type="button">
        <a-radio value="START">直播中</a-radio>
        <a-radio value="NEW">未开始</a-radio>
        <a-radio value="END">已结束</a-radio>
      </a-radio-group>
    </a-row>
    <PickTablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :api="getLiveList"
      :api-params="params"
      :bordered="true"
    >
      <template #endTime="{ record }">
        {{ unixToDate(record) }}
      </template>
      <template #recommend="{ data }">
        <a-switch v-model="data.recommend" @change="star(data)">
          <template #checked> 是 </template>
          <template #unchecked> 否 </template>
        </a-switch>
      </template>
      <template #see="{ data }">
        <a-button @click="getLiveDetail(data)" type="text" status="success">查看 </a-button>
      </template>
    </PickTablePage>
  </a-card>
</template>

<script setup lang="ts">
  import { PickTablePage } from '@pickmall/ui-v3-components'  
  import { MethodsRule, ColumnsDataRule } from '@/types/global';
  import { getLiveList, whetherStar } from '@/api/promotion';
  import { liveStatus } from '@/utils/tools';
  import { ref, watch, reactive } from 'vue';
  import { unixToDate } from '@/utils/filters';
  import { useRouter } from 'vue-router';

  const router = useRouter();
  const tablePageRef = ref<any>();
  const type = ref<string>('NEW');
  const switched = ref<boolean>(false);

  const columnsTable: ColumnsDataRule[] = [
    {
      title: '直播标题',
      dataIndex: 'name',
    },
    {
      title: '主播昵称',
      dataIndex: 'anchorName',
    },

    {
      title: '直播开始时间',
      dataIndex: 'createTime',
    },
    {
      title: '直播结束时间',
      dataIndex: 'endTime',
      slot: true,
      slotTemplate: 'endTime',
    },
    {
      title: '是否推荐',
      dataIndex: 'recommend',
      slot: true,
      slotTemplate: 'recommend',
    },
    {
      title: '直播状态',
      dataIndex: 'status',
      slot: true,
      slotData: {
        badge: liveStatus,
      },
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 150,
    methods: [
      {
        title: '查看',
        callback: 'see',
        slot: true,
        slotTemplate: 'see',
      },
    ],
  };

  const params = reactive({
    status: type,
  });
  watch(type, (val) => {
    params.status = val;
    tablePageRef.value.init();
  });
  // 是否推荐
  const star = async (val: any) => {
    val.recommend == true ? (switched.value = true) : (switched.value = false);
    const res = await whetherStar({ id: val.id, recommend: switched.value });
    if (res.data.success) {
      tablePageRef.value.init();
    }
  };
  // 查看
  const getLiveDetail = (val: any) => {
    router.push({
      name: 'live-detail',
      query: {
        ...val,
        liveStatus: type.value,
      },
    });
  };
</script>
